package templates

import (
	_const "gitee.com/lstack_light/go-light/internal/pkg/global"
	"log"
	"os"
	"text/template"
)

/**
  @author: light
  @since: 2023/9/3
  @desc: 业务层接口模板
*/

var _ Template = &Service{}

type Service struct {
	Receiver *Receiver
	TemplateParams
}

func (s *Service) Execute(eventType _const.TemplateEventType) error {
	switch eventType {
	case _const.InitEvent:
		return s.Init()
	case _const.GenerateEvent:
		return s.Generate()
	}
	return nil
}
func (s *Service) Init() error {
	serviceData := []byte("package service\n\nimport (\n\t\"{{.Module}}/internal/model/bto\"\n\t\"gitee.com/lstack_light/go-light/pkg/server/respData\"\n)\n\ntype {{.Name}}Service interface{\n\t{{range.Methods}}\n\t{{.Name}}({{.Params}}) *respData.Response\n\t{{end}}\n}")
	err := os.WriteFile(s.TemplateName, serviceData, 0644)
	if err != nil {
		log.Fatal("创建业务层接口模板文件失败：", err)
		return err
	}
	return s.Receiver.next.Execute(_const.InitEvent)
}

func (s *Service) Generate() error {
	file, createErr := os.Create(s.OutputFile)
	if createErr != nil {
		log.Fatal(createErr)
		return createErr
	}
	// 读取模板文件
	tmpl, tempErr := template.ParseFiles(s.TemplateName)
	if tempErr != nil {
		log.Fatal("解析业务层接口模板失败：", tempErr)
		return tempErr
	}
	// 定义引用变量
	type Method struct {
		Name   string
		Params string
	}
	type Temp struct {
		Module  string
		Name    string
		Methods []Method
	}
	// 定义方法列表
	methods := []Method{
		{Name: "FindAll"},
		{Name: "FindOne", Params: "param *bto." + s.Name},
		{Name: "CreateOne", Params: "param *bto." + s.Name},
		{Name: "UpdateOne", Params: "param *bto." + s.Name},
		{Name: "DeleteOne", Params: "param *bto." + s.Name},
	}
	temp := Temp{
		Methods: methods,
		Module:  s.Module,
		Name:    s.Name,
	}
	// 执行模板填充并写入输出文件
	err := tmpl.Execute(file, temp)
	if err != nil {
		log.Fatal(err)
		return err
	}
	// 删除模板文件
	_ = os.RemoveAll(s.TemplateName)
	log.Println("Go文件已生成：", s.OutputFile)
	return s.Receiver.next.Execute(_const.GenerateEvent)
}
